import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_project01/apis/user.dart';
import 'package:flutter_project01/utils/Emitter.dart';
import 'package:flutter_project01/utils/TokenManager.dart';
import 'package:flutter_project01/utils/toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Timer? timer;
  int countDown = 60;
  // 是否在倒计时
  bool isCountingDown = false;
  // 手机号输入框控制器
  final phoneController = TextEditingController();
  // 验证码输入框控制器
  final codeController = TextEditingController();
  // 手机号正则
  final phoneRegExp = RegExp(r'^1[3-9]\d{9}$');
  // 验证码正则
  final codeRegExp = RegExp(r'^\d{6}$');
  _login() async {
    // 获取手机号和验证码
    final phone = phoneController.text;
    final code = codeController.text;
    // 如果手机号或验证码为空, 则提示用户输入
    if (phone.isEmpty || code.isEmpty) {
      PromptAction.showError('请输入手机号和验证码');
      return;
    } else if (!phoneRegExp.hasMatch(phone) || !codeRegExp.hasMatch(code)) {
      PromptAction.showError('请输入正确的手机号和验证码');
      return;
    }
    // 调用借口登陆
    final res = await UserApi.login(phone, code);
    // 保存token
    tokenManager.setToken(res['token'], res['refreshToken']);
    // 提示登陆成功
    PromptAction.showSuccess('登陆成功');
    // 主动刷新个人信息数据
    eventBus.fire(GetUserInfoEvent());
    // 返回上一页
    if (mounted) {
      Navigator.pop(context);
    }
  }

  @override
  void dispose() {
    super.dispose();
    // 清理定时器
    timer?.cancel();
  }

  _startCountdown() {
    // 如果在倒计时中, 则不进行倒计时
    if (isCountingDown) {
      return;
    }
    isCountingDown = true;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        countDown--;
        if (countDown <= 0) {
          timer.cancel();
          countDown = 60;
          isCountingDown = false;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    decoration: InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () async {
                    // 获取并校验手机号
                    final phone = phoneController.text;
                    if (phone.isEmpty) {
                      // 提示用户输入手机号
                      PromptAction.showError('请输入手机号');
                      return;
                    } else {
                      // 校验手机号是否合法
                      if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
                        // 提示用户输入正确的手机号
                        PromptAction.showError('请输入正确的手机号');
                        return;
                      }
                    }
                    // 调用接口发送验证码
                    final res = await UserApi.sendCode(phone);
                    // 延时器
                    Future.delayed(const Duration(seconds: 2), () {
                      // 填充验证码
                      codeController.text = res['code'];
                    });
                    // 开启倒计时
                    _startCountdown();
                  },
                  child: isCountingDown == false
                      ? const Text('获取验证码')
                      : Text('$countDown秒后重新获取'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: codeController,
              decoration: InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
